package com.coffee_shop_app.service;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.coffee_shop_app.common.BaseException;
import com.coffee_shop_app.common.DevDeviceInstance;
import com.coffee_shop_app.common.MdData;
import com.coffee_shop_app.common.ObjectRestResponse;
import com.coffee_shop_app.common.SDCardUtils;
import com.coffee_shop_app.common.Utils;
import com.coffee_shop_app.common.vo.WebsocketVo;
import com.coffee_shop_app.database.PcrDataDatabase;
import com.coffee_shop_app.database.dao.PcrData;
import com.coffee_shop_app.common.exception.PidNotFoundException;
import com.coffee_shop_app.module.SingleObject;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class EmbeddedService {

    private static Context selfCcontext = null;

    private static PcrDataDatabase pcrDataDatabase = null;

    private static final  String webRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.coffee_shop_app/files/";

    public EmbeddedService(Context context){
        selfCcontext = context;
        pcrDataDatabase = new PcrDataDatabase(selfCcontext);
    }

    /**
     *  设备参数信息
     * @param params 文件数据
     *               其他参数
     *               时间戳
     */
    public void checkFileAndSave(Map<String, String> params, Map<String, List<String>> parameters, String IP){
        String time = String.valueOf(System.currentTimeMillis());
        for (int i = 0; i < params.size(); i++) {
            String sign = "files" + (i > 0 ? i  : "");
            if (params.get(sign) == null) {
                continue;
            }
            File file = new File(params.get(sign));
            if (file.exists()) {
                System.out.println(sign + "文件存在");
                // 随机字符 nonceStr
                List<String> paramFileStrList = parameters.get(sign);
                Log.i("upLoadFile", "文件" + paramFileStrList.get(0));
                String filesName = paramFileStrList.get(0).replace("\r\n", " ");
                writeData(file, filesName, time);
                if(filesName.equals("channeldata.json")){
                    savePcrData(file, time, IP);
                }
            }
        }
    }

    /**
     * 拷贝文件到本地迷路
     * @param fileName
     * @param originFile
     * @param time 文件夹名称
     */
    void writeData(File originFile, String fileName, String time){
        SDCardUtils sdCardUtils = new SDCardUtils();
        boolean sdCardExist = false;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //为真则SD卡已装入，
            sdCardExist=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        }
        if (sdCardExist)
        {
            String sdDir = Environment.getExternalStorageDirectory().getAbsolutePath();//获取跟目录
            //查找SD卡根路径
            sdDir.toString();
            Log.e("main","得到的根目录路径:" + sdDir);
            File[] files1;
            files1 = selfCcontext.getExternalFilesDirs(Environment.MEDIA_MOUNTED);
            for(File file:files1) {
                Log.e("main", "得到的全部外存：" + String.valueOf(file));
            }
            String path = webRoot + time + "/";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            sdCardUtils.saveFile(path, (byte[]) Utils.getDataFromFile(originFile), fileName);
        }
    }


    /**
     * 处理实验信息
     * @param file
     * @return
     */
    private void savePcrData(File file, String time, String IP) {
        PcrData pcrData = null;
        try {
            // 获取文件的绝对路径
            String absolutePath = file.getAbsolutePath();
            // 创建FileInputStream对象
            InputStream in = new FileInputStream(absolutePath);
            byte[] bys = new byte[1024];
            int len = 0;
            String line = "";
            while ((len = in.read(bys)) != -1) {
                line += new String(bys, 0, len);
            }
            pcrData = JSON.parseObject(line, PcrData.class);
            Log.i("实验数据[{}]", line);
        } catch (Exception e) {
            e.printStackTrace();
//          throw new JSONFormatException(e.getMessage());
        }
        pcrData.setIp(IP);
        String channels = pcrData.getChannel();
        String deviceNo = pcrData.getDeviceNo().replaceAll("-", "");
        long l = System.currentTimeMillis();
        pcrData.setSerialNo(deviceNo + l);
        pcrData.setChannel(channels);
        pcrData.setLink(time);
        pcrData.setCreateTime(time);
        pcrData.setType(pcrData.getKitNo().substring(4, 6));
        // 获取kit todo 补丁： 兼容kit
        if (!"KIT-00-000000-0000000000".equals(pcrData.getKitNo().trim())) {
            // 生成10位随机数
        //    int randomNum = random.nextInt((int) Math.pow(10, 9));
            
            pcrDataDatabase.insert(pcrData);
            
            // 通知前端设备实验数据
            WebsocketVo websocketVo = new WebsocketVo();
            websocketVo.setDataType("deviceData");
            websocketVo.setUserId(pcrData.getDeviceNo());
            websocketVo.setData(JSON.toJSONString(pcrData));
            SingleObject.getInstance().sendFEMessage(websocketVo);
        }
    }

    /**
     * 校验mdData
     * @return
     */
    private DevDeviceInstance isOkMdData(MdData mdData) throws BaseException {
        ObjectRestResponse response =null;
        if (StringUtils.isEmpty(mdData.getPid())) {
            throw new PidNotFoundException("pid为空或参数为空");
        }
        Long time = mdData.getTime();
        long currenttime = System.currentTimeMillis();
//        if (Math.abs(currenttime - time) > 3 * 60 * 1000) {
//            throw new TimePassException("数据已经过期");
//        }
//        // 校验秘钥
//        response =  embeddedService.getByCode(mdData.getPid());
//        if(!response.getRel()){
//            throw new PCRNotFoundException("pcr主机不存在");
//        }
        return null;
    }

    /**
     * 获取所有的实验数据
     * @return
     */
    public java.util.List<PcrData> getPcrDataList(){
        java.util.List<PcrData> pcrDataList = pcrDataDatabase.queryList("");
        return pcrDataList;
    }

    /**
     * 通过id实验数据
     * @return
     */
    public PcrData getPcrDataById(String id){
        // String sql = " where serial_no = " + id;   // 真特么傻
        // String sql = " where serial_no like " + "'%" + id + "%'";
        String sql = " where serial_no = '" + id + "'";
        PcrData pcrData = pcrDataDatabase.query(sql);
        return pcrData;
    }

    /**
     * 根据检测项目查询实验数据
     * @return
     */
    public java.util.List<PcrData> getPcrDataByChipnameCN(String chipnameCN){
        String sql = " where chipname_c_n like " + "'%" + chipnameCN + "%'";
        java.util.List<PcrData> pcrDataList = pcrDataDatabase.queryList(sql);
        return pcrDataList;
    }

    /**
     * 根据检测样品查询实验数据
     * @return
     */
    public java.util.List<PcrData> getPcrDataBySampleNo(String sampleNo){
        String sql = " where sample_no like " + "'%" + sampleNo + "%'";
        java.util.List<PcrData> pcrDataList = pcrDataDatabase.queryList(sql);
        return pcrDataList;
    }

    /**
     * 根据检测样品查询实验数据
     * @return
     */
    public java.util.List<PcrData> getPcrDataByStartTime(Long startTime){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(startTime));
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        Date beginOfDate = calendar.getTime();

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(new Date(startTime + 3600 * 24 * 1000));
        endCalendar.set(endCalendar.get(Calendar.YEAR), endCalendar.get(Calendar.MONTH), endCalendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        Date endOfDate = endCalendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(formatter.format(beginOfDate));  //今日System.out.println(formatter.format(beginOfDate));


        String sql = " where start_time > " + beginOfDate.getTime() + " and start_time < " + endOfDate.getTime();
        java.util.List<PcrData> pcrDataList = pcrDataDatabase.queryList(sql);
        return pcrDataList;
    }

//    // 处理设备号
//    List<String> paramPidList = parameters.get("pid");
//                if (paramPidList.size() == 0) {
//        return newFixedLengthBidResponse("缺少数据");
//    }
//                Log.i("upLoadFile", "设备编号为" + paramPidList.get(0));
//    String pid = paramPidList.get(0).replace("\r\n", " ");
//
//    // 处理加密字符 sign
//    List<String> paramSignList = parameters.get("sign");
//                if (paramSignList.size() == 0) {
//        return newFixedLengthBidResponse("缺少数据");
//    }
//                Log.i("upLoadFile", "标志符号" + paramSignList.get(0));
//    String sign = paramSignList.get(0).replace("\r\n", " ");
//
//    // 处理加密字符 time
//    List<String> paramTimeList = parameters.get("time");
//                if (paramTimeList.size() == 0) {
//        return newFixedLengthBidResponse("缺少数据");
//    }
//                Log.i("upLoadFile", "时间戳" + paramTimeList.get(0));
//    String time = paramTimeList.get(0).replace("\r\n", " ");
//
//    // 随机字符 nonceStr
//    List<String> paramNonceStrList = parameters.get("nonceStr");
//                if (paramNonceStrList.size() == 0) {
//        return newFixedLengthBidResponse("缺少数据");
//    }
//                Log.i("upLoadFile", "随机字符" + paramNonceStrList.get(0));
//    String nonceStr = paramNonceStrList.get(0).replace("\r\n", " ");
//
//    // 业务字符 params
//    List<String> paramParamsStrList = parameters.get("params");
//                if (paramParamsStrList.size() == 0) {
//        return newFixedLengthBidResponse("缺少数据");
//    }
//                Log.i("upLoadFile", "业务字符" + paramParamsStrList.get(0));
//    String paramParams = paramParamsStrList.get(0).replace("\r\n", " ");

    public static void main(String[] args) {
    }
}
